import { Button, message, notification, Space } from 'ant-design-vue'
import { defineComponent, ref } from 'vue'
import { useRoute } from 'vue-router'

import { couponApi } from '@/apis'
import type { CodeItem } from '@/apis/couponTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { download, optionsToMap } from '@/utils'

export default defineComponent({
  name: 'CodeLibrary',
  setup() {
    const statusOptions = [
      { label: '未下发', value: 0 },
      { label: '已下发', value: 1 },
      { label: '已失效', value: 2 }
    ]
    const statusMap = optionsToMap(statusOptions)

    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        toolbarConfig: {
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '关键字',
              field: 'keyword',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '用户昵称或手机号'
                }
              }
            },
            {
              title: '状态',
              field: 'status',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部状态'
                },
                options: statusOptions
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columns: [
          {
            type: 'checkbox',
            width: 50
          },
          {
            title: '码值',
            field: 'name'
          },
          {
            title: '下发用户',
            field: 'user'
          },
          {
            title: '下发时间',
            field: 'deriveTime',
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '领券时间',
            field: 'receiveTime',
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '状态',
            field: 'status',
            formatter: ({ cellValue }) => {
              return statusMap[cellValue]
            }
          },
          {
            title: '操作',
            width: 200,
            slots: {
              default: 'operation'
            }
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await couponApi.getCodeList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                couponId: route.query.id,
                ...form
              })
              return data
            }
          }
        },
        checkboxConfig: {
          checkMethod: ({ row }) => {
            return row.status !== 2
          }
        }
      }
    } as ProTableProps)

    const route = useRoute()
    const { showConfirm } = useDialog()

    function handleBatchInvalid() {
      const selected = tableRef.value.table.getCheckboxRecords().map(v => v.id)

      if (selected.length === 0) {
        return message.warn('请选择至少1条记录')
      }

      showConfirm({
        content: '确认批量作废？',
        onOk: () => {
          tableRef.value.refresh(async () => {
            await couponApi.invalidCodeList(selected)
            notification.success({
              message: '批量作废成功',
              duration: 1.5
            })
          })
        }
      })
    }

    function handleInvalid(item: CodeItem) {
      showConfirm({
        content: '确认作废？',
        onOk: () => {
          tableRef.value.refresh(async () => {
            await couponApi.invalidCodeList([item.id])
            notification.success({
              message: '作废成功',
              duration: 1.5
            })
          })
        }
      })
    }

    function handleExport() {
      const { form } = tableRef.value.table.getProxyInfo()!

      tableRef.value.refresh(async () => {
        const res = await couponApi.exportCodeList({
          ...form,
          couponId: route.query.id
        })
        download(res, '码库列表')
      })
    }

    return {
      tableRef,
      tableConfig,
      handleBatchInvalid,
      handleInvalid,
      handleExport
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleInvalid(row)}
                  disabled={row.status === 2}
                >
                  作废
                </Button>
              </Space>
            ),
            toolbarButtons: () => (
              <Space>
                <Button onClick={this.handleExport}>导出码库</Button>
                <Button onClick={this.handleBatchInvalid}>批量作废</Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
